<?php
namespace Duobao\Controller;

use Duobao\Model\PartnerModel as Partner;
use Duobao\Model\PartnerModel;
use Com\Weixin\Pay\unit\JsApiPay as JsApiPay;
use Duobao\Controller\LogController as Mylog;
use Duobao\Model\DBConfModel as DBConf;

class PartnerController extends ControllerBase{
    /**
     * 默认
     */
    public function index()
    {
        echo "<!--hi , i'm from " . MODULE_NAME . "~" . APP_STATUS, "-->";
    }

    /**
     * 显示合伙人分享二维码页面
     */
    public function showPartner(){
        #验证token是否存在，如果token不存在就跳转到前端页面
        $token = I('get.token');
        //$token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.IjE0MDoxNDUzOTYwMTg3Ig.3eImjgijaEGV8qZ5049-wGbqHbcW-lGp9mV03fxZbvI';
        if(empty($token)){
            header("Location:".C('FRONT_URL')."/?c=user");
        }else{
            $this->assign('rooturl',C('APP_URL'));
            $this->assign('token',$token);
            $this->assign('title',C('APP_NAME'));
            $this->display('default/user_partner');
        }
    }

    /**
     * 合伙人中心显示的数据
     * 需要的数据用户的token
     */
    public function userPartner(){
        $ret = array();
        $ret['status'] = 200;
        $ret['msg'] = '';
        $ret['data'] = array();

        try{
            #获取用户的id
            $uid = $this->getUid(I('get.token'));
            if(is_numeric($uid)){
                #返回用户名和图像
                $model = new Partner();
                $userMsg = $this->getUserMsg($model,$uid);
                $ret['data']['user'] = $userMsg;
                $ret['data']['userid'] = $uid;

                $commission = $this->getCommission($model,$uid);
                $ret['data']['com'] = $commission;

                $partner = $this->getPartnerData($model,$uid);
                $ret['data']['part'] = $partner;
            }else{
                #token失效或者token无效返回false
                E($uid,403);
            }
        }catch (\Exception $e){
            $ret['status'] = $e->getCode();
            $ret['msg'] = $e->getMessage();
        }

        return $this->response($ret);
    }

    /**
     * 获取用户的佣金信息
     */
    private function getCommission($model,$uid){
        return $model->getCommission($uid);
    }

    /**
     * 考虑到使用member的分别获取用户名和图像的数据库操作是两次操作，故在才直接定义了一个方法返回用户的姓名和图像
     */
    private function getUserMsg($model,$uid){
        return $model->getUserMsg($uid);
    }

    /**
     * 获取合伙人和佣金的数据
     */
    private function getPartnerData($model,$uid){
        return $model->getPartnerData($uid);
    }

    /**
     * 显示专属二维码页面
     */
    public function showQrcode(){
        $uid = I('get.uid');
        $this->assign('uid',$uid);
        $this->assign('title',C("APP_NAME"));
        $this->assign('shareDesc','快来成为我的夺宝合伙人，和我一起参加夺宝，一起赚取收益.');

        ##判断用户是否是系统用户,防止恶意用户无限生成二维码
        $member = M('member');
        $condition['uid'] = $uid;
        $data  = $member->where($uid)->find();
        if($data){
            #本地调试兼容性处理
            $imgurl = C('APP_URL');
            $exist = strpos($imgurl,'index.php/Duobao');
            if($exist){
                #去除字符串
                $imgurl = str_replace('index.php/Duobao','',$imgurl);
            }
            $this->assign('imgurl',$imgurl);
            $this->assign('rooturl',C('APP_URL'));
            $this->assign('fronturl',C('FRONT_URL'));
            #读取数据库配置中的wx_qrcode
            $dbcof = new DBConf();
            $this->assign('shareImg',$dbcof->getConfField('wx_qrcode'));
            $this->display('default/my_qrcode');
        }else{
            $this->error('用户不存在');
        }
    }
    /**
     * 生成专属二维码
     */
    public function productQrcode(){
        $ret = array();
        $ret['status'] = 200;
        $ret['msg'] = '';
        $ret['data'] = array();

        try{
            $uid = I('get.uid');
            if(empty($uid)){
                E('发生了一个错误',403);
            }else{
                $model = new PartnerModel();
                $result = $model->productQrcode2($uid);
                if($result){
                    $ret['data']['img'] = $result;
                    $ret['data']['url'] = C('APP_URL').'/Partner/showBind/?uid='.$uid;
                }else{
                    E('二维码生成失败',403);
                }
            }
        }catch (\Exception $e){
            $ret['status'] = $e->getCode();
            $ret['msg'] = $e->getMessage();
        }

        return $this->response($ret);
    }

    /**
     * 显示绑定的页面
     */
    public function showBind(){
        $uid = I('get.uid');
        #查看用户id在数据库中是否是存在的，如果不存在直接不请求微信的openid
        $openid = '';
        #exist能否发生绑定的标志
        if(empty($uid)){
            $this->assign('exist',false);
        }else{
            $member = M('member');
            $condition['uid'] = $uid;
            $result = $member->where($condition)->find();
            #判断当前uid是否是我们数据库中的人
            if(!$result){
                $this->assign('exist',false);
            }else{
                #对老用户进行限定，已经已经关注公众号的无法绑定给其他的用户
                $jsapipay = new JsApiPay();
                $openid = $jsapipay->GetOpenid();

                #判断openid是否获取成功，如果获取成功将其与openid进行绑定插入到partner下
                if(!$openid){
                    $this->assign('exist',false);
                }else{
                    #1、首先判断当前获取的openid不是用户自己,使用一个比较简单粗暴的方式，直接查看用户的openid在user表中是否存在，如果存在
                    $user = M('user');
                    $condition2['openid'] = $openid;
                    $result2 = $user->where($condition2)->find();
                    if($result2){
                        $this->assign('exist',false);
                    }else{
                        #需要判断用户是否已经产生二维码
                        $partner = M('partner');
                        $condition3['uid'] = $uid;
                        $result3 = $partner->where($condition3)->find();
                        if(!$result3){
                            $this->assign("exist",false);
                        }else{
                            #在partner_relationship中查看pid和openid是否已经存在，如果已经存在
                            $partnerrs = M('partner_relationship');
                            #先查看openid在数据库中是否存在已经绑定的对象
                            $condition5['openid'] = $openid;
                            $condition5['bind_status'] = 1;
                            $result5 = $partnerrs->where($condition5)->find();
                            if($result5){
                                #如果存在已经绑定的关系，直接返回false,防止一个用户绑定多个上级
                                $this->assign('exist',false);
                            }else{
                                $condition4['pid'] = $uid;
                                $condition4['openid'] = $openid;
                                $result4 = $partnerrs->where($condition4)->find();
                                #如果用户在合伙人关系表中存不存在，插入一条数据
                                if(!$result4){
                                    $data['pid'] = $uid;
                                    $data['openid'] = $openid;
                                    $partnerrs->add($data);
                                    $this->assign("exist",true);
                                }else{
                                    $this->assign("exist",true);
                                }
                            }
                        }

                    }
                }
            }
        }

        $this->assign("openid",$openid);
        $this->assign('uid',$uid);
        $this->assign('title',C("APP_NAME"));
        $this->assign('rooturl',C('APP_URL'));
        $this->display('default/bind');
    }

    public function getWeixinQrcode(){
        $ret = array();
        $ret['status'] = 200;
        $ret['msg'] = '';
        $ret['data'] = array();

        try{
            $uid = I('get.uid');
            $qrcode = S('qrcode');
            if($qrcode){
                $ret['data']['qrcode'] = $qrcode;
            }else{
                $model = M('config');
                $condition['name'] = 'wx_qrcode';
                $ret['data']['qrcode'] = $model->where($condition)->getField('value');
                S('qrcode',$ret['data']['qrcode']);
            }

            #获取好友的图像和名称
            $member = M('member');
            $condition['uid'] = $uid;
            $user = $member->where($condition)->field('img,username')->find();
            $ret['data']['friend_name'] = $user['username'];
            $ret['data']['friend_img'] = $user['img'];
            #获取公众号的图片
        }catch (\Exception $e){
            $ret['status'] = $e->getCode();
            $ret['msg'] = $e->getMessage();
        }

        return $this->response($ret);
    }

    /**
     * 绑定操作
     */
    public function bindOperation(){
        $ret = array();
        $ret['status'] = 200;
        $ret['msg'] = '';
        $ret['data'] = array();

        try{
            #获取openid和uid
            $openid = I('post.mark');
            $pid = I('post.uid');#父级id
            #判断父级id与openid值是否在数据库中记录
            $model = M("partner_relationship");
            $where['pid'] = $pid;
            $where['openid'] = $openid;
            $exist = $model->where($where)->find();
            #判断存在对应关系
            if($exist){
                #获取祖父和曾祖父id
                $gpid = '';
                $ggpid= '';
                $where2['openid'] = $openid;
                $result = $model->where($where2)->getField('pid');
                $where4['uid'] = $pid;
                $result3 = $model->where($where4)->field('pid,gpid')->find();
                if(empty($result3)){
                    $gpid = 0;
                    $ggpid = 0;
                }else{
                    $gpid = $result3['pid'];
                    $ggpid = $result3['gpid'];
                }

                $where3['pid'] = $pid;
                $where3['openid'] = $openid;
                $data['gpid'] = $gpid;
                $data['ggpid'] = $ggpid;
                $data['bind_status'] = 1;
                $result2 = $model->where($where3)->save($data);
                if($result2){
                    $ret['data'] = true;
                }else{
                    $ret['data'] = false;
                }
            }else{
                E('页面发生错误',403);
            }

        }catch (\Exception $e){
            $ret['status'] = $e->getCode();
            $ret['msg'] = $e->getMessage();
        }

        return $this->response($ret);
    }

    /**
     * 计算佣金,crontab测试
     */
    private function calculationCommission(){
        Mylog::write('进入计算佣金的crontab');
        $model = M('member_go_record');
        $condition['time'] = array('gt','1454296907');
        $condition['handle_status'] = 0;
        #获取用户的uid在用户购买记录表中
        $result = $model->where($condition)->field('id,moneycount,uid')->limit(10)->order('id')->select();
        if(!$result){
            return false;
        }

        #获取用户的金额和uid，根据uid对上层分钱
        $relationship = M('partner_relationship');
        $model2 = new \Think\Model();
        $dbconf = new DBConf();

        #开启事务

        foreach($result as $value){
            $model2->startTrans();

            $condition2['uid'] = $value['uid'];
            $result2 = $relationship->where($condition2)->field('pid,gpid,ggpid')->find();

            #判断是否存在上级id，如果存在上级id，进行分钱，不存在上级id，就直接不分钱,设置处理状态为2表示没有上级元素
            if($result2){
                #计算核心佣金
                $h_com = $value['moneycount'] * $dbconf->getConfField('core_ratio');
                #更新核心合伙人佣金
                $query1 = $model2->execute("update __PREFIX__partner set `t_commission` = `t_commission`+$h_com,`s_commission`=`s_commission`+$h_com,`h_partner`=`h_partner`+$h_com where uid=".$result2['pid']);

                #更新高级合伙人佣金
                if($result2['gpid'] != 0){
                    $m_com = $value['moneycount'] * $dbconf->getConfField('adv_ratio');
                    $query2 = $model2->execute("update __PREFIX__partner set `t_commission` = `t_commission`+$m_com,`s_commission`=`s_commission`+$m_com,`m_partner`=`m_partner`+$m_com where uid=".$result2['gpid']);
                }else{
                    $query2 = true;
                }

                #跟新普通合伙人佣金
                if($result2['ggpid'] != 0){
                    $s_com = $value['moneycount'] * $dbconf->getConfField('general_ratio');
                    $query3 = $model2->execute("update __PREFIX__partner set `t_commission` = `t_commission`+$s_com,`s_commission`=`s_commission`+$s_com,`s_partner`=`s_partner`+$s_com where uid=".$result2['ggpid']);
                }else{
                    $query3 = true;
                }

                $query4 = $model2->execute("update __PREFIX__member_go_record set `handle_status` = 1 WHERE `id` = ".$value['id']);

                if($query1 && $query2 && $query3 && $query4){
                    $model2->commit();
                    Mylog::write('事务成功');
                }else{
                    $model2->rollback();
                    Mylog::write('事务失败回滚');
                }
            }else{
                $query5 = $model2->execute("update __PREFIX__member_go_record set `handle_status` = 2 WHERE `id` = ".$value['id']);
                if(!$query5){
                    Mylog::write($value['uid'].'号用户结算异常');
                }
            }
        }
    }
}